package com.example.a2032.activity;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.a2032.R;
import com.example.a2032.Utils.Utils;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class FindPhoneActivity extends BaseActivity {


    @BindView(R.id.imageView_findPhone)
    ImageView imageViewFindPhone;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.button_stopFind)
    Button buttonStopFind;
    private Vibrator vibrator;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_phone);
        ButterKnife.bind(this);
        KeepScreenOn();
        init();
    }

    private static final String TAG = "FindPhoneActivity";
    Disposable disposable;

    private void init() {
        vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
        vibrator.vibrate(new long[]{100, 100, 100, 1000}, 0);
        mediaPlayer =Utils.startPlayAssetRing(this,"find_phone.mp3");
        Utils.startMeasureTimer(1, new Observer() {
            @Override
            public void onSubscribe(Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(Object o) {
                cancelPlay();
                finish();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KeepScreenOff();
        unSubscribe(disposable);
        cancelPlay();
    }
    boolean isCancel;
    void cancelPlay() {
        if(isCancel)return;
        isCancel=true;
        vibrator.cancel();
        if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
        }



    }

    @OnClick(R.id.button_stopFind)
    public void onViewClicked() {
        cancelPlay();
        finish();
    }
}